package validation;

import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.Set;

/**
 * JSR 303 - Bean Validation 是一个数据验证规范
 */
public class ValidationDemo {

    public static void main(String[] args) {
        Metadata metadata = new Metadata();
        metadata.age = -10;
        metadata.name = "";
        metadata.sex = "f";
        metadata.birthday = new Date();
        metadata.address = "123456789012345678901";
        validate(metadata);
    }

    public static void validate(Object obj){
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        Validator validator = vf.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(obj);
        for(ConstraintViolation<Object> constraintViolation : violations){
            System.out.println(constraintViolation.getPropertyPath() + " " + constraintViolation.getMessage());
        }
    }


    @Data
    public static class Metadata {

        @Min(value = 1, message = "年龄不能小于0")
        private Integer age;

        @NotEmpty(message = "姓名不能为空")
        private String name;

        @Pattern(regexp = "^男$|^女$", message = "性别只能为男或女")
        private String sex;

        @Past(message = "出生日期不能大于当前日期")
        private Date birthday;

        @Length(min = 1, max = 20, message = "地址长度不得大于20字符串")
        private String address;
    }
}
